﻿using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using Space.Model;
using Space.Model.Data;
using Space.Model.Entity;
using Space.Model.Fsm;

namespace Space.Library.Input
{
    public class InputManager
    {
        private static InputManager _instance;

        public static InputManager Instance
        {
            get { return _instance ?? (_instance = new InputManager()); }
        }

        private readonly Queue<Input> _inputQueue = new Queue<Input>();

        private InputManager()
        {

        }

        public void Click(int x, int y, MouseButtons button)
        {
            _inputQueue.Enqueue(new Input(x, y, button));
        }

        public void HandleInput()
        {
            GameRunner gameRunner = GameRunner.Instance;
            while (_inputQueue.Count > 0)
            {
                var item = _inputQueue.Dequeue();
                Point targetPoint = Board.WindowSpaceToBoardSpace(item.X, item.Y);
                var targetEntity = gameRunner.ShipEntities.FirstOrDefault(ent => ent.BoardCoords == targetPoint);

                Ship selectedEntity = gameRunner.SelectedEntity;
                if (item.Button == MouseButtons.Left)
                {
                    if (targetEntity == null)
                    {
                        if (selectedEntity != null)
                            selectedEntity.IsSelected = false;
                    }
                    else if (targetEntity.ShipModel.OwnerType == gameRunner.GameState.CurrentTurnOwner)
                    {
                        targetEntity.IsSelected = true;
                    }
                    return;
                }

                if (item.Button == MouseButtons.Right)
                {
                    if (selectedEntity != null && selectedEntity.Fsm.AcceptInput)
                    {
                        // right click on ship (fire)
                        if (targetEntity != null)
                        {
                            if (targetEntity.ShipModel.OwnerType != gameRunner.GameState.CurrentTurnOwner) // Enemy
                            {
                                selectedEntity.Fsm.ChangeState(new FiringState(targetEntity));
                            }
                        }
                        else // right click on space (move)
                        {
                            selectedEntity.Fsm.ChangeState(new RotateToTargetState(targetPoint));
                        }
                    }
                }
            }
        }
    }
}